import { get } from "./gender.js";
import puppeteer from "puppeteer";
import fs from "fs";
import schedule from "node-schedule";
import { exec } from "child_process";
import cmd from "node-cmd";
import path from "path";

// 获取百度热搜关键词
async function getKeyWords() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("https://www.baidu.com/");
  const keywords = await page.evaluate(() => {
    // 内置浏览器执行的js
    // 这里console.log 是看不到的~
    const doc = document.getElementsByClassName("title-content-title");
    let res = [];
    for (let i = 0; i < doc.length; i++) {
      res.push(doc[i].innerHTML);
    }
    return res;
  });
  return keywords;
}

// 通过keywords生成markdown文件
async function genderMd(keywords) {
  keywords.map(async (key) => {
    let content = `---\ntitle: ${key}\n---\n\n${get(key)}`;
    await fs.writeFileSync(
      `./seo/source/_posts/${key}.md`,
      content,
      "utf8",
      function (err) {
        if (err) {
          return console.error(err);
        }
      }
    );
  });
}

// 运行cmd脚本
function runCmd(cmd) {
  return new Promise((resolve, reject) => {
    exec(
      cmd,
      {
        maxBuffer: 1024 * 2000,
        cwd: path.resolve() + "/seo",
      },
      function (err, stdout, stderr) {
        if (err) {
          console.log(err);
          reject(err);
        } else if (stderr.lenght > 0) {
          reject(new Error(stderr.toString()));
        } else {
          console.log(stdout);
          resolve();
        }
      }
    );
  });
}

async function main() {
  schedule.scheduleJob("0 0 0,10,16 * * ?", async () => {
    // schedule.scheduleJob("1 * * * * *", async () => {
    console.log(new Date());
    const keywords = await getKeyWords();
    genderMd(keywords);
    await runCmd("hexo clean");
    await runCmd("hexo g");
    await runCmd(
      `scp -r ${path.resolve()}/seo/public root@47.102.138.101:/home/demo/seo`
    );
    // await runCmd("hexo d");
  });
}

main();
